<?php

namespace Frieza\Modules\Position\Actions;

use Doraemon\cache\Queue;
use Doraemon\model\AdmOperateLog;
use Doraemon\model\Member;
use Doraemon\model\Member as mMember;
use Doraemon\service\Member as MemberService;
use Encore\Admin\Actions\RowAction;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Doraemon\model\MemberHistoryNick;
use Doraemon\service\User;

class ChangeUsername extends RowAction
{
    public $name = '修改昵称';

    public function handle($uid,Request $request)
    {
        $new_nick = $request->get('new_nick');
        $user_info = Member::getUserInfo($uid);
        $admin_id = Admin::user()->id;
        $admin_name = Admin::user()->username;
        $nick = $user_info['nick'];
        $result = MemberService::nick(true,false, $new_nick, $uid, $user_info['type'],
            true, true, true, true);
        if ($result !== true) {
            return $this->response()->error($result);
        }
//        if (Member::getUidByNick($new_nick)){
//            return $this->response()->error('修改失败,该昵称已存在!');
//        }
        $data['nick'] = $new_nick;
        $rs = MemberService::set_userInfo($uid, $user_info['type'], $data);
        if (empty($rs)) {
            return $this->response()->error('昵称修改失败,请稍后重试!');
        }
        MemberHistoryNick::addHistoryNick($uid,$nick,$new_nick);
        AdmOperateLog::addLog($uid,AdmOperateLog::$operate_type['edit_nick'],$admin_id,$admin_name,$nick,$new_nick);
        $type = $user_info['type'];
        //更新es中的相关信息
        User::updateEsUserInfo($uid);
        Queue::insertQueue('User/delUserinfoCache', array(
            'uid' => $uid,
        ), Queue::QUEUE_COMMON);
        Queue::insertQueue('User/addSearch', array(
            'uid' => $uid,
            'nick' => $new_nick,
            'type' => $type
        ), Queue::QUEUE_COMMON);
        Queue::insertQueue('queue/shop/changeNick', array(
            'uid' => $uid,
        ), Queue::QUEUE_BIZ);
        return $this->response()->success('用户昵称修改成功!')->refresh();
    }

    public function retrieveModel(Request $request)
    {
        if (!$key = $request->get('_key')) {
            return false;
        }

        return $key;
    }

    public function form($request)
    {
        $this->text('new_nick', '新昵称')->required()->help('昵称只能是中文、英文、数字、中划线-、下划线_;中文2~12字;英文/数字4~24字符;不能纯数字');

    }
}
